import { Injectable } from '@angular/core';
import { Request, RequestOptionsArgs, Response, URLSearchParams, RequestOptions, ConnectionBackend, Headers, Jsonp } from '@angular/http';
import 'rxjs';
import { Observable } from 'rxjs';
import { ConfigService } from './config.service';
import { ToolService } from './tool.service';
import * as $ from 'jquery';
import { Platform } from '@ionic/angular';
@Injectable({
  providedIn: 'root'
})
export class HttpService extends Jsonp {
  /**
   * 如果传递的URL有协议就直接访问，没有协议的URL就听见默认的一个配置的域名或者ip
   */
  public baseUrl: string = ConfigService.SERVER_PATH + "";//请求的ip
  public version: string = ConfigService.APP_VERSION + "";//接口的版本号,用APP的版本来区分
  public isShowUrl: boolean = ConfigService.IS_SHOW_CONSOLE_URL;

  constructor(
    backend: ConnectionBackend,
    defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  /**
   * 请求拦截器
   */
  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    let urlStr: string = '';
    if (typeof url === 'string') {
      urlStr = url;
    } else {
      urlStr = url['url'];
    }
    if (this.needContextPrefix(urlStr)) {
      typeof url === 'string' ? (url = this.baseUrl + '' + url) : (url['url'] = this.baseUrl + '' + url['url']);
    }
    return this.intercept(super.request(url, this.getRequestOptionArgs("post", options)), false);
  }
  /**
   * get拦截器param:any,
   */
  get(url: string, param?: any, options?: RequestOptionsArgs): Observable<Response> {
    //参数拼接
    let token = $("app-root").attr("token");
    let sessid = $("app-root").attr("sessid");
    let uid=$("app-root").attr("uid");
    let encrypt = (!ToolService.isEmpty($("app-root").attr("encrypt")) && $("app-root").attr("encrypt")=='1') ? 1 : 0;
    let baseParam;
    if (ToolService.isEmpty(sessid)) {
      baseParam = { "token": ToolService.isEmpty(token) ? "" : token, "encrypt": encrypt,"uid": uid,"v": this.version};
    } else {
      baseParam = { "token": ToolService.isEmpty(token) ? "" : token, "sessid": sessid, "encrypt": encrypt ,"uid": uid,"v": this.version};
    }
    //let baseParam={};
    if (ToolService.isEmpty(param)) {
      url = ToolService.Urlsplice(baseParam, url);
    } else {
      let concatParam = ToolService.concat(baseParam, param);
      url = ToolService.Urlsplice(concatParam, url);
    }
    if (this.isShowUrl) {
      console.log("requireURL:", url);
    }
    return this.intercept(super.get(url, this.getRequestOptionArgs('get', options)), true);
  }

  /**
   * put拦截器
   */
  put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    if (body == null) {
      body = new URLSearchParams();
    }
    return this.intercept(super.put(url, body.toString(), this.getRequestOptionArgs('put', options)), true);
  }

  /**
   * post拦截器
   */
  post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    if (body == null) {
      body = new URLSearchParams();
    }
    //  body.set('version', this.version);
    if (this.isShowUrl) {
      console.log("requireURL:", url, "body:", body.toString());
    }
    return this.intercept(super.post(url, body.toString(), this.getRequestOptionArgs('post', options)), true);
  }

  /**
   * file post拦截器
   */
  filePost(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    if (body == null) {
      body = new URLSearchParams();
    }
    return this.intercept(super.post(url, body, this.getRequestOptionArgs('post', options)), true);
  }

  /**
   * delete拦截器
   */
  delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.intercept(super.delete(url, this.getRequestOptionArgs('delete', options)), true);
  }

  /**
   * 判断是否需求在请求地址前加上IP地址
   */
  needContextPrefix(url: string): boolean {
    return !(url.indexOf('./assets') === 0 || url.indexOf('http') === 0);
  }

  /**
   * 添加请求头信息
   */
  getRequestOptionArgs(type: string, options?: RequestOptionsArgs, token?: string): RequestOptionsArgs {
    if (options == null) {
      options = new RequestOptions();
    }
    if (options.headers == null) {
      options.headers = new Headers();
      options.withCredentials = true;
      if (type === 'post' || type === 'put') {
        options.headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
      }
      if (!ToolService.isEmpty(token)) {
        options.headers.append("access-token", token);
      }
    }
    return options;
  }

  /**
   * 捕获应答异常并处理
   */
  intercept(observable: Observable<Response>, isReqType: boolean): Observable<Response> {
    if (isReqType) {
      // observable=observable.do((res: Response) => {}, (res) => {
      //   if (res.status === -1 || res.status === 0) {
      //     res._body = '网络异常，请稍后再试';
      //   } else if (res.status === 401) {
      //     res._body = null;
      //   } else if (res.status === 404) {
      //     res._body = '资源未找到';
      //   } else if (res.status === 502) {
      //     res._body = '网络异常';
      //   } else if (res.status === 503) {
      //     res._body = '连接数过多，请稍后...';
      //   } else {
      //     if (res._body != null && /\w+[\s\.]\w+/.test(res._body)) {
      //       res._body = '系统异常';
      //     }
      //   }
      // });
    }
    return observable;
  }
  /**
   * 隐藏加载的进度
   */
  hideLoading() {
    // PopwinService.eventsShare.publish("hideLoading");
  }
  /**
   * 显示加载
   * @param msg 加载中的文字提示
   * @param isShow  为空或者为true则显示加载
   */
  showLoading(msg?: string, isShow?: Boolean) {
    if (ToolService.isEmpty(isShow) || isShow) {
      let msgV = ToolService.isEmpty(msg) ? "加载中..." : msg
      // PopwinService.eventsShare.publish("showLoading",msgV);
    }
  }
  /**
   * 使用方式列举
   * get的传递参数的情况
   * lotResNet() {
      let that = this;
      let obj= "{\"code\":\""+that.code+"\"}";
      this.http.get(UrlService.USER_GAMSYS, { "callback": "JSONP_CALLBACK", "data":ToolService.aesEncode(obj) }).subscribe(res => {
        let data = res.json();
        if(data.code==ConfigService.SUCCESS_CODE){
          that.lotRes = ToolService.aesDecodeToJson(data.data);
          that.isLotRes=true;
        }else{
          that.isLotRes=false;
        }
      }, error => {
          this.popWin.toast(ToolService.newError(error));
      });
    }
  *
   *  this.http.get(UrlService.TEST,{"callback":"JSONP_CALLBACK"}).subscribe(res=>{
          console.log(res);
          let data = res.json();
       },error=>{
          console.log("error",error);
       });
    *完善
        menuNet(type:number=1){
      let that=this;
      let obj= "{\"type_code\":\""+type+"\"}";  
      this.http.get(UrlService.USER_MAIN_HALL,{"callback":"JSONP_CALLBACK","data":ToolService.aesEncode(obj)}).subscribe(res=>{
        let data = res.json();
        if(data.code==ConfigService.SUCCESS_CODE){
            //成功的逻辑
        }else if(data.code==ConfigService.FAIL_CODE){
            this.popWin.toast(data.message);
        }else if(data.code==ConfigService.LOGIN_CODE){
            this.navCtrl.navigateForward("/login");
        }
     },error=>{
        console.log("error",error);
     });
    }
    *   
   */
}
